package so.shanku.essential.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.CommentsAdapter;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.Utils;
import striveen.util.used.view.view.XListView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/10/6 0006.
 */
public class FindCommentsActivity extends BaseUIActivity {

	//商品评论
	@ViewInject(id = R.id.goods_comments_xlv)
	private XListView goods_comments_xlv;
	@ViewInject(id = R.id.nodata_layout) //无数据
	private LinearLayout nodataLayout;
    @ViewInject(id=R.id.empty)
    private TextView emptyTv;
	private CommentsAdapter goodsCommentsAdapter;

	/**
	 * 评论输入框，和发送按钮
	 */
	@ViewInject(id = R.id.comment_edit)
	private EditText pro_et_comment;
	@ViewInject(id = R.id.comment_submit, click = "commit_comment_click")
	private TextView comment_submit;
	@ViewInject(id = R.id.layout_comment)
	private RelativeLayout layout_comment_submit;
	/**
	 * 评论后标识
	 */
	private int iscomment = 0;
	/**
	 * 回复某人的信息
	 */
	private String reId;
	/**
	 * 平乱
	 */
	private List<JsonMap<String, Object>> commentsDatas;
	private int commentsCurrentPage = 0;
	private int pageSize = 10;

	private String discoredId;//发现id
	private String commentId;
	private int flag = 0;//0:发现详情进入

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_comments_layout);
		pro_et_comment.setFocusableInTouchMode(true);
        emptyTv.setText(R.string.no_comments);
		initData(getIntent());
	}


	private void initData(Intent intent) {
		goodsCommentsAdapter = new CommentsAdapter(this);
		discoredId = intent.getStringExtra(ExtraKeys.Key_Msg1);
		setCenter_title(intent.getStringExtra(ExtraKeys.Key_Msg2));
        commentId = intent.getStringExtra(ExtraKeys.Key_Msg4);
		try {
			flag = intent.getIntExtra(ExtraKeys.Key_Msg3, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (flag == 0) {
			getCommentList(true);
		} else {
			getCommentsById(true);
			setBtn_menuText(R.string.scan_article, onClickListener);
		}
		goodsCommentsAdapter.setFlag(flag);
		//getCommentsById(true); //test
		reId = "0";
		goods_comments_xlv.setXListViewListener(loadXListViewMoreListener);
		goods_comments_xlv.setPullRefreshEnable(true);
		goods_comments_xlv.setPullLoadEnable(true);
		goods_comments_xlv.setOnItemClickListener(
				new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
						if (position < 1) {
							return;
						}
						String userInfoId = commentsDatas.get(position - 1).getStringNoNull("UserInfoId");

						if (userInfoId.equalsIgnoreCase(Utils.getUserId(mContext))) {
							toast.showToast(R.string.index_nocomment);
							pro_et_comment.setText("");
							pro_et_comment.setHint(R.string.comment_submit_hint);
							reId = "0";
						} else {
							String Rename = commentsDatas.get(position - 1)
									.getStringNoNull("Name");
							pro_et_comment.setHint("回复：" + Rename);
							reId = commentsDatas.get(position - 1).getStringNoNull("Id");
							pro_et_comment.requestFocus();

							InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//隐藏软键盘
// imm.hideSoftInputFromWindow(editView.getWindowToken(), 0);
//显示软键盘
							imm.showSoftInput(pro_et_comment, InputMethodManager.SHOW_FORCED);
//切换软键盘的显示与隐藏
							//imm.toggleSoftInputFromWindow(pro_et_comment.getWindowToken(), 0, InputMethodManager.HIDE_NOT_ALWAYS);
//					}

							//}
						}
					}
				}
		);
	}

	/**
	 * 查看原文
	 */
	View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
            Intent intent = new Intent(mContext, FindDetailActivity.class);
            intent.putExtra(Constant.ID, discoredId);
            jumpTo(intent, false);
		}
	};

    /**
	 * 加载评论
	 */
	private XListView.IXListViewListener loadXListViewMoreListener = new XListView.IXListViewListener() {
		@Override
		public void onRefresh() {
			if (flag == 0) {
				getCommentList(true);
			} else {
				getCommentsById(true);
			}
		}

		@Override
		public void onLoadMore() {
			if (flag == 0) {
				getCommentList(false);
			} else {
				getCommentsById(false);
			}
		}
	};

	/**
	 * 获取评论
	 */

	public void getCommentList(boolean chearAllData) {
		if (chearAllData) {
			commentsCurrentPage = 0;
		}
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);

		params.put("DiscoverId", discoredId);
		// params.put("EventId", nowShowProgram);
		params.put("currentPage", commentsCurrentPage + 1);
		params.put("pageSize", pageSize);

		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_GetDiscoverCommentsList);
		queue.setParamsNoJson(params);
		queue.setCallBack(callBack);

		queue.setWhat(GetDataConfing.What_GetDiscoverCommentsList);
		getDataUtil.getData(queue);

	}

	/**
	 * 提交评论
	 *
	 * @param view
	 */
	public void commit_comment_click(View view) {
		if (TextUtils.isEmpty(pro_et_comment.getText())) {
			//toast.showToast(R.string.comment_content_isnull);
			return;
		}
		if (!Utils.isHasLogin(mContext)) {
			gotoLogin();
			return;
		} else {
			getAddComment();
		}

	}

	/**
	 * 添加评论       {DiscoverId:1,Content:"xxxxxx",UserInfoId:9392}
	 *
	 * @param
	 * @return void 返回类型
	 * @throws
	 * @Title: getAddComment
	 * @Description: TODO作用：评论
	 */
	public void getAddComment() {
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);

		params.put("DiscoverId", discoredId);
		params.put("UserInfoId", Utils.getUserId(this));
		params.put("Content", pro_et_comment.getText());
		params.put("DiscoverCommentId", reId);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_GetDiscoverComment);
		queue.setParamsNoJson(params);
		queue.setCallBack(callBack);
		queue.setWhat(GetDataConfing.What_GetDiscoverComment);
		getDataUtil.getData(queue);

	}

	/**
	 * 获取回复的列表 {currentPage:1,pageSize:10,DiscoverId:5,CommentId:54}
	 *
	 * @param chearAllData
	 */
	private void getCommentsById(boolean chearAllData) {
		if (chearAllData) {
			commentsCurrentPage = 0;
		}
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("DiscoverId", discoredId);
		// params.put("EventId", nowShowProgram);
		params.put("currentPage", commentsCurrentPage + 1);
		params.put("pageSize", pageSize);
		params.put("CommentId", commentId);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_GetDiscoverCommentsListMessage);
		queue.setParamsNoJson(params);
		queue.setCallBack(callBack);
		queue.setWhat(GetDataConfing.What_GetDiscoverCommentsListMessage);
		getDataUtil.getData(queue);
	}


	private void validateData() {
		if (commentsDatas == null || commentsDatas.isEmpty()) {
			goods_comments_xlv.setVisibility(View.GONE);
			nodataLayout.setVisibility(View.VISIBLE);
			return;
		} else {
			goods_comments_xlv.setVisibility(View.VISIBLE);
			nodataLayout.setVisibility(View.GONE);
		}
	}

	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {
				if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
					if (entity.what == GetDataConfing.What_GetDiscoverComment) {
						pro_et_comment.setText("");
						pro_et_comment.setHint(R.string.comment_submit_hint);
						reId = "0";
						iscomment = 1;
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//隐藏软键盘
// imm.hideSoftInputFromWindow(editView.getWindowToken(), 0);
//显示软键盘
						imm.hideSoftInputFromWindow(pro_et_comment.getWindowToken(), 0);
						getCommentList(true);
					} else if (entity.what == GetDataConfing.What_GetDiscoverCommentsList || entity.what == GetDataConfing.What_GetDiscoverCommentsListMessage) {
						List<JsonMap<String, Object>> commentsDatas_temp = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
						setCommentsListData(commentsDatas_temp);
						validateData();
					}
				}
			} else {
				ShowGetDataError.showNetError(mContext);
			}
			loadingToast.dismiss();
			goods_comments_xlv.stopLoadMore();
			goods_comments_xlv.stopRefresh();
		}

	};

	private void setCommentsListData(List<JsonMap<String, Object>> commentsDatas_temp) {
		if (commentsDatas_temp.size() == 0 || commentsDatas_temp.size() % pageSize != 0) {
			goods_comments_xlv.setPullLoadEnable(false);
		} else {
			goods_comments_xlv.setPullLoadEnable(true);
		}
		if (commentsCurrentPage == 0) {
			this.commentsDatas = commentsDatas_temp;
			goodsCommentsAdapter.setDatas(commentsDatas);
			goods_comments_xlv.setAdapter(goodsCommentsAdapter);
			if (iscomment == 1) {
				goods_comments_xlv.setSelection(0);
				// if (CommentData.size()>3) {
				// mlv_commentList.setSelection(3);
				// } else {
				// mlv_commentList.setSelection(1);
				// }
			}

		} else {
			this.commentsDatas.addAll(commentsDatas_temp);
			goodsCommentsAdapter.notifyDataSetChanged();
		}
		commentsCurrentPage++;
	}

}